package uebung07_h;

import java.awt.image.BufferedImage;

import javax.imageio.ImageIO;
import javax.swing.JFrame;

import tools.ColorConversions;
import tools.Image;
import tools.ShowImage;

public class Guttenberg02 {
	public static void main(String[] args) throws Exception {
		BufferedImage bim1 = ImageIO.read(Guttenberg02.class.getClassLoader().getResourceAsStream("res/im2.png"));
		BufferedImage bim2 = ImageIO.read(Guttenberg02.class.getClassLoader().getResourceAsStream("res/im6.png"));
		
		int[] im1 = ColorConversions.getFastLuminance(bim1.getRGB(0, 0, bim1.getWidth(), bim1.getHeight(), new int[bim1.getWidth()*bim1.getHeight()], 0, bim1.getWidth()), new int[bim1.getWidth()*bim1.getHeight()]);
		int[] im2 = ColorConversions.getFastLuminance(bim2.getRGB(0, 0, bim2.getWidth(), bim2.getHeight(), new int[bim2.getWidth()*bim2.getHeight()], 0, bim2.getWidth()), new int[bim2.getWidth()*bim2.getHeight()]);
		
		
		int win = 2, im1w = bim1.getWidth(), im2w = bim2.getWidth(), im1h = bim1.getHeight(), im2h = bim2.getHeight();

		double[] disparityMap = new double[im1w*im1h];
		
		int dispmin = 0, dispmax = 64; 
		double[] sums = new double[dispmax*2+1];
		double threshold = 50000;
		
		for (int y = win, endy = im1h-win; y<endy; y++) {
			for (int x = win, endx = im1w-win; x<endx; x++) {
				for (int disparity = -dispmax; disparity<dispmax; disparity++) {
					double sum = 0;
					for (int a = -win; a<win; a++) {
						for (int b = -win; b<win; b++) {
							if (x+b+disparity<im1w && x+b+disparity>0) {
								int lum = im1[x+b+(y+a)*im1w], lumshift = im2[x+b+(y+a)*im1w+disparity];
								double var = lum-lumshift;
								sum += var*var;
							}
							else {
								sum += 512*512;
							}
						}
					}
					sums[disparity+dispmax] = sum;
				}
				double min = Double.POSITIVE_INFINITY;
				int mindisparity = 0;
				for (int i = -dispmax; i<dispmax; i++) {
					if (min>sums[i+dispmax]) {
						min = sums[i+dispmax];
						mindisparity = i;
					}
					
				}
				if (min<threshold)
					disparityMap[x+y*im1w] = -mindisparity;
				else
					disparityMap[x+y*im1w] = 0;
			} 
		}
		
		JFrame ff = new JFrame();
		ff.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		final BufferedImage bi = new BufferedImage(im1w, im1h, BufferedImage.TYPE_INT_ARGB);
		
		int[] pixels = Image.prepare(disparityMap, new int[im1w*im1h]);
		int[] poxels = Image.buildRGB(pixels, pixels, pixels, new int[disparityMap.length]);
	
 		bi.setRGB(0, 0, bi.getWidth(), bi.getHeight(), poxels, 0, bi.getWidth());
		ff.add(new ShowImage(bi));
		
		ff.pack();
		ff.setVisible(true);
	}
}
